package com.cangmaomao.m_penManage.fragment

import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import com.cangmaomao.lib.action.f_often_conn
import com.cangmaomao.lib.base.BaseFragment
import com.cangmaomao.lib.event.AppEvent
import com.cangmaomao.lib.utils.SPUtil.create
import com.cangmaomao.lib.utils.e
import com.cangmaomao.lib.utils.initRecycler
import com.cangmaomao.lib.utils.toast
import com.cangmaomao.m_penManage.R
import com.cangmaomao.m_penManage.adapter.NearbyAdapter
import com.cangmaomao.m_penManage.bean.BleDeviceData
import com.cangmaomao.m_penManage.config.device
import com.cangmaomao.m_penManage.config.state
import com.cangmaomao.m_penManage.contract.PenManageContract
import com.cangmaomao.m_penManage.presenter.PenMangerPresenter
import com.clj.fastble.BleManager
import com.clj.fastble.data.BleDevice
import kotlinx.android.synthetic.main.fragment_often_connected.*
import me.yokeyword.fragmentation.ISupportFragment
import org.greenrobot.eventbus.EventBus


/**
 * Created by Administrator on 2018/7/11 0011.
 */

class PenMangeFragment : BaseFragment<PenManageContract.ManagePresenter>(), PenManageContract.ManageView {

    private var mac: String? = null
    private var data: BleDeviceData? = null
    private lateinit var nearbyAdapter: NearbyAdapter
    private val nearbyList = mutableMapOf<String, BleDevice>()
    private lateinit var bleDevice: BleDevice
    private var ble:BleDeviceData? = null
    private var manager:BleManager?=null


    override val contentViewLayoutID: Int
        get() = R.layout.fragment_often_connected

    @SuppressLint("InflateParams")
    override fun initView(savedInstanceState: Bundle?) {
        initToolBarNav("智能笔管理")

        if (!_mActivity.packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            toast("当前设置不支持BLE蓝牙功能!")
            pop()
        }

        PenMangerPresenter(this)

        if (p.checkBleState()) {
            showConnectSuccess(device!!)
        } else {
            mac = create("BleConfig").get("mac", "") as String
        }

        initRecycler(nearbyRecycler)
        manager = BleManager.getInstance()
        manager!!.init(_mActivity.application)
        manager!!.enableLog(true)
                .setReConnectCount(1, 5000)
                .setConnectOverTime(20000).operateTimeout = 5000

        val isOpen = create("BleConfig").get("open", false) as Boolean

        iv_manage.isChecked = isOpen

        initDevicesView(isOpen)

        iv_manage.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                iv_manage.isChecked = true
                create("BleConfig").add("open", true)
                initDevicesView(true)
            } else {
                BleManager.getInstance().cancelScan()
                iv_manage.isChecked = false
                create("BleConfig").add("open", false)
                initDevicesView(false)
            }
        }
    }

    override fun initDevicesView(flag: Boolean) {
        if (!flag) {
            ble_list.visibility = View.GONE
        } else {
            p.startScan()
            ble_list.visibility = View.VISIBLE
            nearbyAdapter = NearbyAdapter()
            nearbyRecycler.adapter = nearbyAdapter
            nearbyAdapter.setOnItemClickListener { _, any, i ->
                data = any as BleDeviceData
                any.isFlag = true
                p.connect(any.bleDevice.mac)
                nearbyAdapter.notifyItemChanged(i)
                var bundle = Bundle()
                bundle.putParcelable("BleDeviceData", data)
                EventBus.getDefault().post(AppEvent(f_often_conn, bundle))
            }
        }
    }

    override fun onFragmentResult(requestCode: Int, resultCode: Int, data: Bundle?) {
        super.onFragmentResult(requestCode, resultCode, data)
        if (resultCode == ISupportFragment.RESULT_OK){
            if (requestCode==100){
                 ble =data!!.getParcelable("BleDeviceData") as BleDeviceData
                if (ble!!.isOften){
                    //断开已经连接的蓝牙
                    manager!!.disconnect(this.bleDevice)
                    e("之前连接蓝牙的名字 "+this.bleDevice.name)
                    p.connect(ble!!.bleDevice.mac)
                    e("现在要连接蓝牙的名字 "+ble!!.bleDevice.name+"  修改过后的名字  " +ble!!.newsName)
                }
            }
        }
    }

    override fun devices(bleDevice: BleDevice) {
        if (!TextUtils.isEmpty(mac)) {
            if (bleDevice.mac == mac!!) {
                p.connect(bleDevice.mac)
                return
            }
        }
        if (nearbyList[bleDevice.mac] == null) {
            nearbyList[bleDevice.mac] = bleDevice
            nearbyAdapter.addData(BleDeviceData(false, bleDevice))
            nearbyAdapter.notifyDataSetChanged()
        }
    }

    override fun connectState(flag: Boolean, bleDevice: BleDevice) {
        if (flag) {
            nearbyList.remove(bleDevice.mac)
            nearbyAdapter.data.remove(data)
            nearbyAdapter.notifyDataSetChanged()
            showConnectSuccess(bleDevice)
            state = 0
            device = bleDevice
            create("BleConfig").add("mac", bleDevice.mac)
        }
    }

    override fun showConnectSuccess(bleDevice: BleDevice) {
        already_connected.visibility = View.VISIBLE
        if (ble==null){
            d_name.text = bleDevice.name
        }else{
            d_name.text= ble!!.newsName
        }
        this.bleDevice =bleDevice
    }

    override fun onPause() {
        super.onPause()
        BleManager.getInstance().cancelScan()
    }

    override fun onRightClick() {

    }
}
